import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfo } from './api'

Vue.use(Vuex)

// 获取localStorage中的信息
const getInitUserInfo = () => {
  const userInfoText = localStorage.getItem('userInfo')
  if (userInfoText) {
    return JSON.parse(userInfoText)
  } else {
    return {}
  }
}

export default new Vuex.Store({
  state: {
    user: getInitUserInfo(),
    bankCardPromoteOnce: true,
    isHasData: false
  },
  mutations: {
    setUser (state, userInfo) {
      state.user = userInfo
      const objText = JSON.stringify(userInfo)
      localStorage.setItem('userInfo', objText)
    },
    deleteUserInfo (state) {
      localStorage.setItem('userInfo', '') // 登出时删除本地信息
      state.user = {}
    },
    promoteOnce (state) {
      state.bankCardPromoteOnce = false
    },
    hasData (state) {
      state.isHasData = true
    }
  },
  actions: {
    userInfo ({ commit }, acctKey) {
      getUserInfo(acctKey, (userData) => {
        commit('setUser', userData)
      })
    }
  }
})
